﻿using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Web.Mvc;
using CRM.Op.Common;
using System.Web.Mvc.Filters;
using CRM.Infrastructure.Service;

namespace CRM.Op.Controllers
{
    public class BaseController : Controller
    {
        #region 系列化/反序列化

        /// <summary>
        /// 将对象转换成JSON
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected string SerializeObject(object value)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            return JsonConvert.SerializeObject(value, Formatting.Indented, timeFormat);
        }

        /// <summary>
        /// 将JSON字符串转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        protected T DeserializeObject<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value);
        }

        #endregion

        #region 重写返回

        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnAuthentication(AuthenticationContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Count() > 0)
            {
                return;
            }

            //验证用户是否登陆
            CurrentUser usr = FormsPrincipal.IsAuthenticated();
            if (usr == null || usr.UserId == 0)
            {
                filterContext.Result = new RedirectResult(Url.Action("Login", "Account"));
            }
            //缓存用户信息
            ViewBag.UserName = usr.UserName;
            ViewBag.RoleID = usr.RoleID;
            ViewBag.CompanyName = usr.CompanyName;

            base.OnAuthentication(filterContext);
        }

        /// <summary>
        /// 重写JsonResult
        /// 由于自带的JsonResult不支持DataTable等对象的序列化
        /// 所以手动构建JsonResult
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        protected ContentResult ReturnResult(object result)
        {
            ContentResult cr = new ContentResult
            {
                ContentType = "application/json",
                Content = SerializeObject(result)
            };
            return cr;
        }

        /// <summary>
        /// 异常记录
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            new ErrorLogService().Insert(new Infrastructure.Entity.ErrorLog()
            {
                CreatedDate = DateTime.Now,
                ErrorMessage = filterContext.Exception.Message,
                ErrorSource = filterContext.Exception.Source,
                ErrorTrace = filterContext.Exception.StackTrace,
                Platform = 3,
                RequestUrl = filterContext.HttpContext.Request.Url.PathAndQuery
            });
            base.OnException(filterContext);
        }

        /// <summary>
        /// 执行完毕
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            new ActionLogService().Insert(new Infrastructure.Entity.ActionLog()
            {
                CreatedDate = DateTime.Now,
                Platform = 3,
                RequestUrl = filterContext.HttpContext.Request.Url.PathAndQuery
            });
            base.OnActionExecuted(filterContext);
        }

        #endregion

        #region Request参数

        /// <summary>
        /// 获取回传参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetParam(string name)
        {
            string value = "";
            if (Request.HttpMethod == "POST")
            {
                value = Request.Form[name];
            }
            if (string.IsNullOrEmpty(value))
            {
                value = Request.QueryString[name];
            }
            if (value == null)
            {
                value = "";
            }
            return value;
        }

        /// <summary>
        /// 获取指定类型参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        protected T GetParam<T>(string name)
        {
            var param = GetParam(name);
            if (string.IsNullOrEmpty(param))
            {
                return default(T);
            }
            return DeserializeObject<T>(param);
        }

        #endregion

        #region 登陆用户
        /// <summary>
        /// 当前登陆用户信息
        /// </summary>
        public CurrentUser CurrentUser
        {
            get
            {
                return FormsPrincipal.IsAuthenticated();
            }
        }
        #endregion
    }
}
